﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMSGSC.DAL;
using PMSGSC.BLL;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Localization;
using System.Linq;
using System.Data.Linq;
using PMSGSC.Common;
using DevExpress.XtraEditors.Controls;
using System.IO;
using System.Diagnostics;
namespace PMSGSC.App
{
    public partial class frmRevisionJob : DevExpress.XtraEditors.XtraForm
    {
        public frmRevisionJob(JobDescription jobDescr)
        {
            InitializeComponent();
            revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescr.JobDescription_ID);
            jobDescription = jobDescr;
        }
        private JobDescription jobDescription;
        private Revision objRevision;
        private Status status = Status.Update;
        //Hiển thị số thứ tự của gridview
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl2.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescription.JobDescription_ID);
                    status = Status.Update;
                }
            }

        }
        // Đặt lại trạng thái update 
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                status = Status.Update;
            }
        }

        private void revisionBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            objRevision = revisionBindingSource.Current as Revision;
            if (null != objRevision)
            {
                ucRichEditControl1.richEditControl1.Text = objRevision.Detail;
                if (ucRichEditControl1.isChange)
                    objRevision.Detail = ucRichEditControl1.richEditControl1.Text;
            }
        }

        private void dataNavigator1_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.EndEdit:
                    if (XtraMessageBox.Show("Are you sure want to approve this ?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
                    {
                        objRevision.Status = "Active";
                        objRevision.ApprovedBy = "TiNi";
                        if (objRevision.Revision_ID != 0)
                        {
                            Revisions_BLL.Update(objRevision);
                            jobDescription.Status = "Active";
                        }
                        else
                        {
                            jobDescription.NameJD = objRevision.Title;
                            jobDescription.RevisionNumber = objRevision.RevisionNumber;
                            objRevision.JobDescription_ID = jobDescription.JobDescription_ID;
                            Revisions_BLL.Insert(objRevision);
                        }
                        JobsDescription_BLL.Update(jobDescription);
                    }
                    break;
                case NavigatorButtonType.CancelEdit:
                    if (XtraMessageBox.Show("Are you sure want to delete this revision ?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
                    {
                        if (revisionBindingSource.Count == 1)
                        {
                           bool r =  Revisions_BLL.Delete(objRevision);
                           bool d =  JobsDescription_BLL.Delete(jobDescription);
                        }
                        else
                        {
                            bool t =  Revisions_BLL.Delete(objRevision);
                            if (jobDescription != null)
                                revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescription.JobDescription_ID);

                            jobDescription.NameJD = objRevision.Title;
                            jobDescription.RevisionNumber = objRevision.RevisionNumber;
                            JobsDescription_BLL.Update(jobDescription);
                        }
                    }
                    break;
            }
        }
        private void gridView2_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = (GridView)sender;
            status = Status.New;
            GridColumn NumberCol = view.Columns["RevisionNumber"];
            GridColumn StatusCol = view.Columns["Status"];
            GridColumn DateCol = view.Columns["CreateDate"];
            GridColumn CreateCol = view.Columns["CreateBy"];
            int revCount = revisionBindingSource.Count ;
            view.SetRowCellValue(e.RowHandle, NumberCol, revCount);
            view.SetRowCellValue(e.RowHandle, StatusCol, "Draft");
            view.SetRowCellValue(e.RowHandle, DateCol, DateTime.Now.Date);
            view.SetRowCellValue(e.RowHandle, CreateCol, "TiNi");

        }

        private void btnSaveAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ucRichEditControl1.isChange)
            {
                objRevision.Detail = ucRichEditControl1.richEditControl1.Text;
                ucRichEditControl1.isChange = false;
            }
            if (XtraMessageBox.Show("Are you sure you want to upate a Revision?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                foreach (Revision re in revisionBindingSource.Cast<Revision>().ToList())
                {
                    bool result = Revisions_BLL.Update(re);
                }
                revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescription.JobDescription_ID);
            }
        }

        private void gridView2_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;
            if (!view.IsNewItemRow(view.FocusedRowHandle))
                e.Cancel = true;
            GridColumn StatusCol = view.Columns["Status"];
            GridColumn DateCol = view.Columns["CreateDate"];
            GridColumn CreateCol = view.Columns["CreateBy"];
            GridColumn ApprovedCol = view.Columns["ApprovedBy"];
            if (view.IsNewItemRow(view.FocusedRowHandle) && ((view.FocusedColumn == StatusCol) || (view.FocusedColumn == DateCol)
                || (view.FocusedColumn == CreateCol) || view.FocusedColumn == ApprovedCol))
            {
                e.Cancel = true;
            }

        }

        private void gridView2_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            if (status == Status.New)
            {
                objRevision.JobDescription_ID = jobDescription.JobDescription_ID;
                bool result = Revisions_BLL.Insert(objRevision);
                if(!result)
                    XtraMessageBox.Show("Insert Unsuccess !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (e.Page.Name == "xtraTabPage3")
            {
                if(objRevision != null)
                    revisionAttachmentBindingSource.DataSource = RevisionAttachment_BLL.GetDataByRevisionID(objRevision.Revision_ID, false);
            }
        }
        #region RevisionAttachment

        private byte[] StreamFile(string fileName)
        {
            // Open file
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // ByteArray
            byte[] ImageData = new byte[fs.Length];

            // Read block of bytes
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

            // Close it
            fs.Close();

            // Return the byte data
            return ImageData;
        }
        public bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream fileStream = new System.IO.FileStream
                    (fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                // Writes a block of bytes
                fileStream.Write(byteArray, 0, byteArray.Length);

                // Close file stream
                fileStream.Close();

                return true;
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.ToString());
            }
            return false;
        }
        private bool isChangedA;
        private void RevisionAttachmentBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedA = true;
        }
        private void repositoryItemButtonEdit2_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                OpenDocument();
            }
            catch { }
        }
        private void btnUploadFile_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (gridView18.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "Select one file upload";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {

                    string fileName = openFileDialog.InitialDirectory + openFileDialog.FileName;
                    FileInfo fileInfo = new FileInfo(fileName);
                    long sizeFile = fileInfo.Length / 1000;
                    if (sizeFile <= 3000)
                    {
                        string extension = Path.GetExtension(fileName);
                        RevisionAttachment.Extension = extension;
                        byte[] fileByteArray = StreamFile(fileName);
                        // Converts it to Binary
                        // it can be done inside the method as well
                        Binary fileBinary = new Binary(fileByteArray);
                        RevisionAttachment.ContentFile = fileBinary;
                        GridColumn AttachExtension = gridView18.Columns["Extension"];
                        extension = extension.ToUpper();
                        gridView18.SetRowCellValue(gridView18.FocusedRowHandle, AttachExtension, extension);
                    }
                    else
                    {
                        XtraMessageBox.Show("The size file  must be less than 3M ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        // Khai báo trạng thái mặc định 
        private Status statusRevisionAttachment = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private RevisionAttachment RevisionAttachment = new RevisionAttachment();
        //Hiển thị số thứ tự của gridview
        private void gridViewA_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        LockMouseClickEvent lockMouseClick = new LockMouseClickEvent();
        private void gridViewA_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveRevisionAttachmentToDatabase();
        }
        private void SaveRevisionAttachmentToDatabase()
        {
            if (TestBeforeAddRevisionAttachment())
            {
                frmProcessBar pb = new frmProcessBar();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    LoadSkinToForm();
                    pb.ShowDialog();
                }
                ));
                if (statusRevisionAttachment == Status.Update)
                {
                    thread.Start();
                    bool result = RevisionAttachment_BLL.Update(RevisionAttachment);
                    if (!result)
                    {
                        XtraMessageBox.Show("Update Unsuccess !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    revisionAttachmentBindingSource.DataSource = RevisionAttachment_BLL.GetDataByRevisionID(objRevision.Revision_ID, isChangedA);
                    isChangedA = false;

                }

                if (statusRevisionAttachment == Status.New)
                {
                    thread.Start();
                    RevisionAttachment.Revision_ID = objRevision.Revision_ID;
                    bool result = RevisionAttachment_BLL.Insert(RevisionAttachment);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    statusRevisionAttachment = Status.Update;
                }

                if (pb.InvokeRequired)
                    pb.BeginInvoke(new Action(() => pb.Close()));
            }
        }

        private bool TestBeforeAddRevisionAttachment()
        {
            return objRevision != null ? true : false;
            //throw new NotImplementedException();
        }
        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Blue");
            }
        }
       
        private void DeleteRevisionAttachment(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                RevisionAttachment = revisionAttachmentBindingSource.Current as RevisionAttachment;
                bool result = RevisionAttachment_BLL.Delete(RevisionAttachment);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Handled = true;
                }
                revisionAttachmentBindingSource.DataSource = RevisionAttachment_BLL.GetDataByRevisionID(objRevision.Revision_ID, isChangedA);
                isChangedA = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridViewA_KeyDown(object sender, KeyEventArgs e)
        {
            if (TestBeforeAddRevisionAttachment())
            {
                if (e.KeyCode == Keys.Delete)
                {
                    if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        RevisionAttachment = revisionAttachmentBindingSource.Current as RevisionAttachment;
                        bool result = RevisionAttachment_BLL.Delete(RevisionAttachment);
                        if (!result)
                        {
                            XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            e.Handled = true;
                        }
                        revisionAttachmentBindingSource.DataSource = RevisionAttachment_BLL.GetDataByRevisionID(objRevision.Revision_ID, isChangedA);
                        isChangedA = false;
                    }
                    else
                    {
                        e.Handled = true;
                    }
                }
            }
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewA_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (TestBeforeAddRevisionAttachment())
            {
                statusRevisionAttachment = Status.New;
            }
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewA_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (RevisionAttachment != null)
            {
                GridView view = (GridView)sender;
                GridColumn AttachName = view.Columns["Name"];
                GridColumn AttachCode = view.Columns["Code"];
                GridColumn AttachContent = view.Columns["ContentFile"];

                if (null == view.GetRowCellValue(e.RowHandle, AttachName))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachName;
                    e.ErrorText = "Please enter the RevisionAttachment Name. ";
                    view.SetColumnError(AttachName, "RevisionAttachment Name is not empty");
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Please enter the RevisionAttachment Code. ";
                    view.SetColumnError(AttachCode, "RevisionAttachment Code is not empty");
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachContent))
                {
                    e.Valid = false;
                    e.ErrorText = "Please upload one file into table ";
                }
                RevisionAttachment = revisionAttachmentBindingSource.Current as RevisionAttachment;
                RevisionAttachment.Revision_ID = objRevision.Revision_ID;
                if (RevisionAttachment_BLL.IsExits(RevisionAttachment))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "RevisionAttachment Code is exits. ";
                    view.SetColumnError(AttachCode, "RevisionAttachment Code is exits");
                }
            }
        }
        private void RevisionAttachmentBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            RevisionAttachment = revisionAttachmentBindingSource.Current as RevisionAttachment;
        }
        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewA_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {

            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl2.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    revisionAttachmentBindingSource.DataSource = RevisionAttachment_BLL.GetDataByRevisionID(objRevision.Revision_ID, isChangedA);
                    isChangedA = false;
                }
            }
        }
        // Đặt lại trạng thái update 
        private void gridViewA_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusRevisionAttachment = Status.Update;
            }
        }
        private void OpenDocument()
        {
            if (gridView18.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                string Address = Application.StartupPath + "\\Attachment\\";
                Directory.CreateDirectory(Address);
                RevisionAttachment = revisionAttachmentBindingSource.Current as RevisionAttachment;
                RevisionAttachment attach = RevisionAttachment_BLL.GetDataById(RevisionAttachment.Attachment_ID);

                if (null != attach)
                {
                    string fileName = attach.Name + attach.Extension;
                    Address += fileName;
                    if (ByteArrayToFile(Address, attach.ContentFile.ToArray()))
                    {
                        try
                        {
                            Process.Start(Address);
                        }
                        catch
                        {
                        }
                    }

                }
            }
        }

        #endregion

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescription.JobDescription_ID);
        }

        private void btnApproved_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure want to approve this ?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
            {
                objRevision.Status = "Active";
                objRevision.ApprovedBy = "TiNi";
                Revisions_BLL.Update(objRevision);
                jobDescription.Status = "Active";
                jobDescription.NameJD = objRevision.Title;
                jobDescription.RevisionNumber = objRevision.RevisionNumber;
                JobsDescription_BLL.Update(jobDescription);
            }
        }

        private void gridControl12_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (TestBeforeAddRevisionAttachment())
            {
                switch (e.Button.ButtonType)
                {
                    case NavigatorButtonType.Remove:
                        if (TestBeforeAddRevisionAttachment())
                            DeleteRevisionAttachment(e);
                        break;
                }
            }
        }

        private void gridControl2_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.Remove:
                    if (TestBeforeAddRevisionAttachment())
                        DeleteRevision(e);
                    break;
            }
        }
        private void DeleteRevision(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure want to delete this revision ?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
            {
                Revisions_BLL.Delete(objRevision);
                if (revisionBindingSource.Count == 1)
                {
                    JobsDescription_BLL.Delete(jobDescription);
                    revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescription.JobDescription_ID);
                }
                else
                {
                    revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescription.JobDescription_ID);
                    objRevision = revisionBindingSource.Current as Revision;

                    jobDescription.NameJD = objRevision.Title;
                    jobDescription.RevisionNumber = objRevision.RevisionNumber;
                    jobDescription.Status = objRevision.Status;

                    JobsDescription_BLL.Update(jobDescription);
                }
            }
            e.Handled = true;
        }

        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure want to delete this revision ?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
            {
                Revisions_BLL.Delete(objRevision);
                if (revisionBindingSource.Count == 1)
                {
                    JobsDescription_BLL.Delete(jobDescription);
                    revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescription.JobDescription_ID);
                }
                else
                {
                    revisionBindingSource.DataSource = Revisions_BLL.GetAll(jobDescription.JobDescription_ID);
                    objRevision = revisionBindingSource.Current as Revision;

                    jobDescription.NameJD = objRevision.Title;
                    jobDescription.RevisionNumber = objRevision.RevisionNumber;
                    jobDescription.Status = objRevision.Status;

                    JobsDescription_BLL.Update(jobDescription);
                }
            }
        }

    }
}